package com.itheima;

import org.apache.commons.beanutils.BeanUtils;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.util.Map;

@WebServlet("/addStudent")
public class addStudent extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        try {
            //导入包获取表单提交数据
            Map<String, String[]> map = request.getParameterMap();
            //将数据封装到学生对象中
            Student stu = new Student();
            BeanUtils.populate(stu,map);
            //将文件写入本地文件
            BufferedWriter bw = new BufferedWriter(new FileWriter("D:\\IdeaProjects\\JavaWeb\\day05_Student\\web\\stu.txt",true));
            bw.write(stu.getUsername() + "," + stu.getPassword());
            bw.newLine();
            bw.close();

            //测试数据共享
            request.setAttribute("username",stu.getUsername());
            request.getRequestDispatcher("/DownloadStudent").forward(request,response);

            //重定位到访问的页面
           // response.sendRedirect(request.getContextPath() + "/index.jsp");
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doPost(request, response);
    }
}
